<template>
	<view style="padding-bottom: 150rpx;" class="wrapper bg-linear">
		<view class="wrapper shadow1 border-r-10 bg-color m-b-8 p-8">
			<ppl-textarea placeholder="请输入您的详细需求" @onChange="onChangeNeed">
				<view slot="title" class="t-14">填写信息</view>
			</ppl-textarea>

			<!-- 图片上传组件 -->
			<ppl-upload :initial-files="imgs.split(',').filter(url => url)" @file-change="handleFileChange"
				:max-count="4" @click-preview="handlePreview" />

			<!-- 图片预览组件 -->
			<van-image-preview v-model="showPreview" :images="previewImages" @close="showPreview = false" />

			<ppl-infoField :use-custom="true">
				<view>
					<van-field :value="address" :required="true" placeholder="请选择收货地址" error-message-align="right"
						:error-message="errors.address" is-link clickable readonly input-align="right"
						@click-input="toSelectAddress">
						<view slot="label" class="color8">
							收货地址
						</view>
					</van-field>
					<van-field :value="bonus" :required="true" placeholder="输入金额" error-message-align="right"
						:error-message="errors.bonus" input-align="right" @change="onChangeBonus">
						<view slot="label" class="color8">
							金额
						</view>
					</van-field>
				</view>
			</ppl-infoField>
		</view>
		<ppl-tips :tips="tips" />
		<ppl-pay @submit="submit" :price="price" />
		<ppl-kd :show="showSelectors" @close="close" @onSelected="onSelected" position="bottom" />
		<van-popup :show="show" @close="show = false" position="bottom">
			<van-picker :show-toolbar="true" :columns="columns" @change="onChangeTime" @confirm="confirmTime" />
		</van-popup>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow,
		onUnload
	} from '@dcloudio/uni-app';
	import {
		ref,
		reactive,
		watch,
		computed
	} from 'vue'
	import {
		postNeed
	} from '@/api/index.js'
	import {
		DELIVERYTIME,
		GENDER
	} from '@/package/constants/index.js'
	import {
		getList,
		payFlag
	} from '@/utils/index.js'

	import {
		getPaymentInfoTo,
		getYueZhiFu
	} from '@/api/index.js'

	import {
		addPrintingOrders,
		updatePrintingOrders,
		deletePrintingOrders
	} from '@/package/api/insertList.js'

	// 地址相关响应式数据
	const address = ref(''); // 显示的收货地址（楼栋 + 详细地址）
	const selectedAddress = ref(null); // 完整的地址对象
	let addressListener = null; // 存储收货地址事件监听器引用

	// 获取当前用户ID
	const userId = ref(uni.getStorageSync('userId') || '');

	// 初始化所有响应式数据
	const checked = ref(true)
	const bonus = ref('')
	const price = ref(0);
	const cid = ref('');
	const name = ref('');
	const showSelectors = ref(false);
	const show = ref(false)
	const columns = ref([]);
	const currentSelect = ref('');
	const need = ref('');
	const tips = ref(['这里只用付款跑腿费', '打印内容可以发送到对方微信', '打印的费用私信付给楼栋管理员', '请提前下好单，联系电话留对，及时与楼栋管理员沟通',
		'发布需要实名认证审核通过'
	])
	const errors = reactive({
		address: '',
		bonus: ''
	});

	// 图片相关数据
	const imgs = ref(''); // 存储图片URL，用逗号分隔
	const showPreview = ref(false); // 控制预览组件显示
	const previewImages = ref([]); // 预览的图片数组

	// 价格计算
	const updatePrice = () => {
		price.value = bonus.value ? Number(bonus.value) : 0;
	}

	// 金额变更
	const onChangeBonus = (e) => {
		bonus.value = e.detail;
		if (bonus.value) errors.bonus = '';
		updatePrice();
	}

	// 选择地址
	const toSelectAddress = () => {
		console.log('准备跳转到收货地址选择页面');

		// 移除旧监听器
		if (addressListener) {
			uni.$off('selectAddress', addressListener);
			uni.$off('selectPickAddress', addressListener);
			addressListener = null;
		}

		// 新建监听器 - 处理完整的地址对象
		addressListener = (res) => {
			if (!res) {
				console.error('地址选择返回数据为空');
				return;
			}

			// 保存完整的地址对象
			selectedAddress.value = res;

			// 拼接显示的地址（楼栋 + 详细地址）
			if (res.building || res.detailAddress) {
				address.value = `${res.building || ''} ${res.detailAddress || ''}`.trim();
				errors.address = '';
			} else if (res.address) {
				address.value = res.address;
				errors.address = '';
			} else {
				console.error('地址选择返回数据格式异常:', res);
			}
		};

		// 绑定事件
		uni.$on('selectAddress', addressListener);
		uni.$on('selectPickAddress', addressListener);

		// 跳转地址页
		uni.navigateTo({
			url: '/package/pages/address/address?isPickAddress=true',
			success: () => console.log('成功跳转地址页'),
			fail: (err) => console.error('跳转失败:', err)
		});
	}

	// 关闭弹窗
	const close = () => {
		showSelectors.value = false;
	}

	// 需求变更
	const onChangeNeed = (e) => {
		need.value = e.detail;
	}

	// 图片上传处理
	const handleFileChange = (fileUrls) => {
		console.log('接收到图片URL列表:', fileUrls);
		imgs.value = fileUrls.join(',');
		console.log('更新后的图片URL:', imgs.value);
	};

	// 处理图片预览
	const handlePreview = (index, urls) => {
		previewImages.value = urls;
		showPreview.value = true;
	};

	// 从地址中提取楼栋信息
	const getBuildingFromAddress = (address) => {
		if (!address) return '';
		const parts = address.split(' ');
		return parts.length > 0 ? parts[0] : '';
	}

	// 从地址中提取详情地址
	const getDetailFromAddress = (address) => {
		if (!address) return '';
		const parts = address.split(' ');
		return parts.length > 1 ? parts.slice(1).join(' ') : address;
	}

	// 提交订单
	const submit = async () => {
		console.log(uni.getStorageSync('login_data'))
		console.log(selectedAddress.value)
		// 表单验证
		if (!address.value) {
			errors.address = '请选择收货地址';
			return;
		}
		if (!bonus.value) {
			errors.bonus = '请输入金额';
			return;
		}
		// 从本地存储中获取查看是否实名
		if (uni.getStorageSync('login_data').isrealnameauthenticated != 1) {
			// 表示未实名
			uni.showToast({
				title: '未进行实名认证,不能发布任务',
				icon: 'none',
				duration: 1000
			});
		}

		try {
			// 获取完整的地址信息
			const fullAddress = selectedAddress.value || {};
			const userInfo = uni.getStorageSync('login_data') || {};

			// 构建订单参数（使用完整的地址信息）
			const orderParams = {
				id: null, // 自增ID由数据库生成
				description: need.value, // 简介
				userName: userInfo.nikeName || '',
				imageUrl: imgs.value, // 使用imgs代替imageUrls
				receiverName: fullAddress.name || '', // 收货人姓名（优先使用地址选择的姓名）
				receiverPhone: fullAddress.phone || '', // 收货人电话（优先使用地址选择的电话）
				receiverBuilding: fullAddress.building || getBuildingFromAddress(address.value), // 收货人楼栋
				receiverDetail: fullAddress.detailAddress || getDetailFromAddress(address.value), // 收货人详情地址
				paymentAmount: price.value, // 支付金额
				paymentMethod: null, // 支付方式（支付后更新）
				userId: userId.value, // 用户ID
				buildingId: fullAddress.buildingId || uni.getStorageSync("selectedBuilding"), // 楼栋ID
				orderStatus: 0, // 订单状态（0-待支付）
				schoolId: uni.getStorageSync('school_id'), // 学校id
				schoolName: uni.getStorageSync('school_name'), // 学校名称
				buildingName: uni.getStorageSync('selectedBuildingText') // 楼栋名称
			};

			console.log('提交的订单参数:', JSON.stringify(orderParams));

			// 调用API
			const addRes = await addPrintingOrders(orderParams);
			console.log('订单添加响应:', addRes);

			if (addRes.data > 0) {
				const orderId = addRes.data; // 获取订单ID

				// 显示支付方式
				uni.showActionSheet({
					itemList: ['微信支付', '余额支付'],
					success: (res) => {
						switch (res.tapIndex) {
							case 0:
								handleWechatPay(orderId, orderParams);
								break;
							case 1:
								handleBalancePay(orderId, orderParams);
								break;
						}
					},
					fail: (err) => {
						console.log('支付方式显示失败:', err);
						handleWechatPay(orderId, orderParams);
					}
				});
			} else {
				uni.showToast({
					title: addRes.msg || '订单添加失败',
					duration: 1000,
					icon: 'none'
				});
			}
		} catch (e) {
			console.error('订单提交异常:', e);
			uni.showToast({
				title: '操作失败，请重试',
				duration: 1000,
				icon: 'none'
			});
		}
	}

	// 余额支付
	const handleBalancePay = async (orderId, orderParams) => {
		try {
			const payParams = {
				orderId: orderId,
				totalAmount: price.value.toFixed(2)
			};

			uni.showLoading({
				title: '支付处理中...'
			});
			const payRes = await getYueZhiFu(payParams);
			uni.hideLoading();

			if (payRes.code === 200) {
				// 更新订单支付方式
				orderParams.paymentMethod = '余额支付';

				uni.showModal({
					title: '支付结果',
					content: payRes.message || '余额支付成功',
					success: async () => {
						// 更新订单状态和支付方式
						await updatePrintingOrders({
							id: orderId,
							paymentMethod: '余额支付',
							orderStatus: 1 // 待打印
						});

						resetForm();
						uni.switchTab({
							url: '/pages/index/index'
						});
					}
				});
			} else if (payRes.code === 400) {
				uni.showToast({
					title: '余额不足',
					icon: 'none'
				});
				deletePrintingOrders(orderId);
			}
		} catch (error) {
			console.error('余额支付异常:', error);
			uni.showToast({
				title: '支付处理失败',
				duration: 1000,
				icon: 'none'
			});
		}
	};

	// 微信支付
	const handleWechatPay = async (orderId, orderParams) => {
		try {
			const payData = {
				orderId: orderId
			};
			const payRes = await getPaymentInfoTo(payData);

			if (payRes.code === 200) {
				// 更新订单支付方式
				orderParams.paymentMethod = '微信支付';

				wx.requestPayment({
					...payRes.data.jsConfig,
					success: async () => {
						// 更新订单状态和支付方式
						await updatePrintingOrders({
							id: orderId,
							paymentMethod: '微信支付',
							orderStatus: 1 // 待打印
						});

						resetForm();
						uni.navigateTo({
							url: '/pages/order/orderDetail?id=' + orderId
						});
					},
					fail: async () => {
						await deletePrintingOrders(orderId);
						uni.showToast({
							title: '支付已取消',
							duration: 1000,
							icon: 'none'
						});
					}
				});
			}
		} catch (error) {
			console.error('微信支付异常:', error);
			uni.showToast({
				title: '支付处理失败',
				duration: 1000,
				icon: 'none'
			});
		}
	};

	// 重置表单
	const resetForm = () => {
		address.value = '';
		bonus.value = '';
		need.value = '';
		imgs.value = ''; // 重置图片
		price.value = 0;
		Object.keys(errors).forEach(key => errors[key] = '');
	};

	// 生命周期钩子
	onShow(() => {
		if (!userId.value) userId.value = uni.getStorageSync('userId') || '';
	});

	onLoad((options) => {
		name.value = options.name || '';
		cid.value = options.cid || '';
		if (!userId.value) userId.value = uni.getStorageSync('userId') || '';
	});

	onUnload(() => {
		if (addressListener) {
			uni.$off('selectAddress', addressListener);
			uni.$off('selectPickAddress', addressListener);
			addressListener = null;
		}
	});
</script>

<style scoped>
	::v-deep .van-cell {
		padding-left: 0;
		padding-right: 0;
	}

	::v-deep .van-submit-bar__bar {
		justify-content: space-between;
	}

	::v-deep .van-button--danger {
		background-color: #3c91ff;
		border-radius: 10rpx;
	}

	::v-deep .van-submit-bar__bar {
		box-shadow: -2px -1px 5px 0px rgba(0, 0, 0, 0.05);
	}

	::v-deep .input-placeholder {
		color: #3c91ff !important;
	}

	::v-deep .van-cell--required:before {
		left: -7px;
	}

	::v-deep .van-cell:after {
		right: 0;
		left: 0;
	}

	.express-size-btn {
		width: 70px;
		height: 40px;
		line-height: 40px;
		border-radius: 20rpx;
		border: 1px solid #ddd;
		font-size: 22rpx;
		color: #666;
		white-space: nowrap;
		text-align: center;
		background-color: #fff;
		float: left;
		margin-right: 10px;
	}

	.express-size-btn.active {
		border-color: #3c91ff;
		color: #3c91ff;
		background-color: rgba(60, 145, 255, 0.1);
	}
</style>